package com.lm.portlet;

import java.io.IOException;
import java.io.PrintWriter;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.util.bridges.mvc.MVCPortlet;
import com.lm.menus.XmlMenu;

public class VideoPlayerPortlet extends MVCPortlet {
//	These addresses are calles in all the others classes: VideoPlayerPortlet.ADRESSE
	public static final String ADDRESS = "http://damien.benon.emi.u-bordeaux1.fr/ytb/"; // The address where the files are hosted
	public static final String ADDRESS_IMAGE = "img/"; // The address/folder where the images are hosted
	public static final String ADDRESS_VIDEO = ""; // The address/folder where the videos are hosted
	public static final String ADDRESS_XML = ""; // The address/folder where the videos are hosted

    public void doView(RenderRequest renderRequest,  
        RenderResponse renderResponse) throws IOException, PortletException {  
        //Render Logic.  
        super.doView(renderRequest, renderResponse);
     }

    // Ajax management
    public void serveResource(ResourceRequest request, ResourceResponse response)
            throws PortletException, IOException {

            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            
            String jsonObj = "";
        	
            switch (request.getParameter("reqType")) {
            case "getJsonMenu": // Called each times the users click on a slider-image
			jsonObj = XmlMenu.getInstance()
					.getXmlMenuByRef(getReference(request.getParameter("src")))
					.getXmlMenuToJson(request.getParameter("srcKeyFrame"));
                break;
            case "getJsonVideo": // Called only when the video source is changed
			jsonObj = XmlMenu.getInstance()
					.getXmlMenuByRef(getReference(request.getParameter("src")))
					.getXmlKeyFramesToJson();
            	break;
            }
        
        System.out.println(jsonObj);
        
        try {           
            PrintWriter out = response.getWriter();
            out.print(jsonObj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public String getReference(String src) {
    	String file = src.replaceAll(ADDRESS + ADDRESS_VIDEO, "");
    	
    	final int lastPeriodPos = file.lastIndexOf('.');
        if (lastPeriodPos <= 0) { // No period after first character - return name as it was passed in 
            return file;
        } else { // Remove the last period and everything after it
            return file.substring(0, lastPeriodPos);
        }
    }

}
